﻿using System;
using System.Reflection;
using System.Linq;

namespace FluentlyXml.Core.DSL
{
	/// <summary> </summary>
	public class FluentSerializationSpec
	{
		private readonly FluentSerializationConfig _config = new FluentSerializationConfig();

		/// <summary> </summary>
		public void ApplyConfigFrom<T>() where T : FluentSerializationSpec, new()
		{
			var spec = new T();
			_config.MergeFrom(spec._config);
		}

		/// <summary> </summary>
		public ITypeDeserializationSpec<T> WhenDeserializing<T>()
		{
			return new TypeDeserializationSpec<T>(_config);
		}

		/// <summary> </summary>
		public IInitialTypeSerializationSpec<T> WhenSerializing<T>()
		{
			return new TypeSerializationSpec<T>(_config);
		}

		internal FluentSerializationConfig GetConfig()
		{
			return _config;
		}

		public void ApplyAllSpecsFromAssembly(Assembly assembly)
		{
			foreach (var type in assembly.GetTypes().Where(t => typeof(FluentSerializationSpec).IsAssignableFrom(t)))
			{
				var spec = (FluentSerializationSpec)Activator.CreateInstance(type);
				_config.MergeFrom(spec._config);
			}
		}
	}
}